﻿using NewsReader.Helpers.Orm;
using NewsReader.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;

namespace NewsReader.Parsers
{
    internal abstract class Parser
    {
        private static readonly Dictionary<string, Parser> s_parsers = new Dictionary<string,Parser>();

        public IAsyncOperation<string> GetFormattedArticleAsync(Uri originalUri)
        {
            return Task.Factory.StartNew(() =>
            {
                return GetFormattedArticle(originalUri);
            }).AsAsyncOperation();
        }

        public abstract string  GetFormattedArticle(Uri originalUri);

        public abstract string Parse(string json);

        public string UriBase { get; set; }
        public string UserAgent { get; set; }


        public static Parser GetParser(string parserName)
        {
            var nf = NewsFormatter.Named(parserName);

            Parser p;
            lock (s_parsers)
            {
                if (!s_parsers.TryGetValue(nf.Name, out p))
                {
                    var type = Type.GetType(nf.TypeID);
                    if (type == null)
                    {
                        Logger.Log.ErrorFormat("Did not find type definition for type {0}", type);
                    }
                    else
                    {
                        Logger.Log.InfoFormat("Found type definition for type {0}", type);
                        p = (Parser)Activator.CreateInstance(type);
                        p.UriBase = nf.Uri;
                        p.UserAgent = nf.UserAgent;
                        s_parsers[nf.Name] = p;
                    }
                }
            }
            return p;
        }
    }
}
